//
//  ModifyPwdController.m
//  NPS
//
//  Created by jadd on 15/10/13.
//  Copyright © 2015年 jadd. All rights reserved.
//

#import "ModifyPwdController.h"

#define kOldPass      0
#define kNewPass      1
#define kCheckPass    2


#define TEXT_Field CGRectMake(105, 10, self.view.bounds.size.width - 105, 40.0f)



@implementation ModifyPwdController
@synthesize  array;
@synthesize tempValues,textFieldBeingEdited;
@synthesize pwdOld,pwdNew,pwdCheck;


-(IBAction)textFieldDone:(id)sender{
    
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    self.textFieldBeingEdited = textField;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    NSNumber *tagAsNum = [[NSNumber alloc] initWithInteger:textField.tag];
    if(textField.text != nil){
        [tempValues setObject:textField.text forKey:tagAsNum];
    }
    
}



-(BOOL) checkValuesInTextField {
    if (pwdOld == nil) {
        
        [Config showMessage:@"请输入您的原密码!"];
        return false;
    }
    else if (pwdNew == nil) {
   
        [Config showMessage:@"请输入您的新密码!"];
        return false;
    }
    else if ([pwdNew lengthOfBytesUsingEncoding:NSUTF8StringEncoding] < 6){
        [Config showMessage:@"新密码位数不能少于六位!"];
       
        return false;
    }
    else if ([pwdOld isEqualToString:pwdNew]){
        [Config showMessage:@"新密码与原密码相同!"];
        
        return false;
    }
    else if (pwdCheck == nil) {
        [Config showMessage:@"请重复您的新密码!"];
        
        return false;
    }
    else if (![pwdCheck isEqualToString:pwdNew]) {
        [Config showMessage:@"您两次输入的新密码不一致!"];
      
        return false;
    }
    else {
        return true;
    }
    
}


//修改密码事件
-(IBAction)modifyAction:(id)sender
{
    if (textFieldBeingEdited != nil)
    {
        NSNumber *tagAsNum= [[NSNumber alloc] initWithInteger:textFieldBeingEdited.tag];
        [tempValues setObject:textFieldBeingEdited.text forKey: tagAsNum];
        
    }

    for (NSNumber *key in [tempValues allKeys])
    {
        switch ([key intValue]) {
            case kOldPass:
                //除去空格和下划线
                pwdOld = [[tempValues objectForKey:key] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
                break;
            case kNewPass:
                pwdNew = [[tempValues objectForKey:key] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
                break;
            case kCheckPass:
                pwdCheck = [[tempValues objectForKey:key] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
                break;
            default:
                break;
        }
    }
    
   
    bool result = [self checkValuesInTextField];
    if(!result)
    {
        return;
    }
    else
    {
      
        [Config showActivityView];
       
        ModifyPasswordRequest * request = [[ModifyPasswordRequest alloc] initWithData:[Config getUser_id] newPassword:self.pwdNew oldPassword:self.pwdOld];
        
        [RequestHandle startOperationWithRequest:request
                complete:^(id responseObject) {
                    
                    ModifyPasswordRespnse * response = [[ModifyPasswordRespnse alloc] init];
                    response.responseObject = responseObject; //保存登陆数据
                    [Config hideActivityView];
                   
                    while (![[NSUserDefaults standardUserDefaults] synchronize]) {}
              
                    [self backButtonPressed];
                    
                } error:^(NSError *error) {
                    //NSLog(@"%@",error);
                    if(error.code == ERROR_PARA_VERIFIY){

                        RepeatLoginController *controller = [[RepeatLoginController alloc] init];
                        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:controller];
                        controller.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
                        [self presentViewController:nav animated:YES completion:^{
                            NSLog(@"");
                        }];

                    }
                    else{
                        [Config showMessage:error.localizedDescription];
                    }
                    
        }];
    }
}


-(void)backButtonPressed{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    //self.edgesForExtendedLayout = UIRectEdgeNone;
    self.tempValues = [[NSMutableDictionary alloc] init];
    dispatch_async(dispatch_get_main_queue(), ^{
        
    });
    self.title = @"修改密码";
    self.tableView.scrollEnabled =NO;
    
    self.array = [[NSMutableArray alloc] initWithObjects:@"原密码",@"新密码", @"确认密码",nil];
    
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom] ;
    button.frame = CGRectMake(0, 0, K_Global_BackButton_Width, K_Global_BackButton_Height);
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [button setImage:[UIImage imageNamed:@"back_white_on"] forState:UIControlStateNormal];
    //[button setImage:[UIImage imageNamed:@"back_white_on"] forState:UIControlStateHighlighted];
    [button addTarget:self action:@selector(backButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.leftBarButtonItem = leftButton;
    
    
    [super viewDidLoad];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return 3;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 60;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, K_ScreenWidth, 100.0f)];
    footView.backgroundColor = CLEAR;
    footView.tintColor = CLEAR;
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    [button setFrame:CGRectMake(K_ScreenWidth *0.04, 50, (K_ScreenWidth -(K_ScreenWidth *0.04*2)), 45.0f)];
    
    [button.layer setMasksToBounds:YES];
    [button.layer setCornerRadius:5.0f];
    [button.layer setBorderWidth:0.5f];
    [button.layer setBorderColor:DEFAULT_LINE_GRAY_COLOR.CGColor];
    button.backgroundColor = [UIColor colorWithHexString:K_Global_ColorHexString_Store];
    
    [button setTitle:@"确 定" forState:UIControlStateNormal];
    UIFont *font = [UIFont systemFontOfSize:20.0];
    
    [button addTarget:self action:@selector(modifyAction:) forControlEvents:UIControlEventTouchUpInside];
    [button.titleLabel setFont:font];
    [button setTitleColor:WHITE forState:UIControlStateNormal];
    [footView addSubview:button];
    return footView;
}

-(CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 100;
}
/*
 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
 {
 
 return 1;
 
 }
 */


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    static NSString *identifier = @"TJCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        
        CGRect cect = TEXT_Field;
      
        UITextField *txtField = [[UITextField alloc] initWithFrame:cect];
        txtField.clearButtonMode = UITextFieldViewModeWhileEditing;
        txtField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        txtField.font = [UIFont systemFontOfSize:18];
        
        txtField.textColor = GRAY;
        [txtField setDelegate:self];
        
        [txtField addTarget:self action:@selector(textFieldDone:) forControlEvents: UIControlEventEditingDidEndOnExit];
        [cell.contentView addSubview:txtField];
        
    }
    
    NSUInteger row = [indexPath row];
    cell.textLabel.text = [self.array objectAtIndex:row];
    
    UITextField *textField = nil;
    
    
    for (UIView *oneView in cell.contentView.subviews)
    {
        if ([oneView isMemberOfClass:[UITextField class]])
            textField = (UITextField *)oneView;
            textField.secureTextEntry = YES;
        
    }
    
    //label.text = [array objectAtIndex:row];
    NSNumber *rowAsNum = [[NSNumber alloc] initWithInteger:row];
    switch (row) {
        case kOldPass:
            textField.placeholder = @"请输入原密码";
            [textField setValue:[UIFont boldSystemFontOfSize:18] forKeyPath:@"_placeholderLabel.font"];
            //[textField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
            if ([[tempValues allKeys] containsObject:rowAsNum])
                textField.text = [tempValues objectForKey:rowAsNum];
            else
                textField.text = @"";
            break;
        case kNewPass:
            textField.placeholder = @"请输入新密码";
            [textField setValue:[UIFont boldSystemFontOfSize:18] forKeyPath:@"_placeholderLabel.font"];
            if ([[tempValues allKeys] containsObject:rowAsNum])
                textField.text = [tempValues objectForKey:rowAsNum];
            else
                textField.text =  @"";
            break;
        case kCheckPass:
            textField.placeholder = @"请再次输入";
            [textField setValue:[UIFont boldSystemFontOfSize:18] forKeyPath:@"_placeholderLabel.font"];
            if ([[tempValues allKeys] containsObject:rowAsNum])
                textField.text = [tempValues objectForKey:rowAsNum];
            else
                textField.text =  @"";
            break;
        default:
            break;
    }
    if (textFieldBeingEdited == textField)
        textFieldBeingEdited = nil;
    
    textField.tag = row;

    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
    
    
}


#pragma mark - Table view delegate
-(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

@end
